const db = require('@/db/db-connection')
const { newRandomId } = require('@/utils/common.util')
const { multipleColumnSet } = require('@/utils/common.util')

class TagModel {
  constructor () {
    this.tableName = 'tag'
  }

  /**
   * find tags
   * @param { String } userId
   * @returns
   */
  async find (userId) {
    try {
      const sql = `SELECT * FROM ${this.tableName} t WHERE t.userId = ?`

      const result = await db.query(sql, [userId])

      return result
    } catch (error) {
      throw new Error(error)
    }
  }

  /**
   * add tag
   * @param { String } name tagName
   * @param { String } folderId pid
   * @param { String } url userId userId
   */
  async add ({ tagName, pid, userId }) {
    try {
      const id = newRandomId()

      const sql = `INSERT INTO ${this.tableName} (id, tagName, pid, userId) VALUES(?, ?, ?, ?)`

      await db.query(sql, [id, tagName, pid, userId])
    } catch (error) {
      throw new Error(error)
    }
  }

  /**
   * update tag
   * @param { String } id
   * @param { String } tagName
   * @param { String } pid
   */
  async update ({ id, tagName }) {
    try {
      const { columnSet, values } = multipleColumnSet({ tagName })

      const sql = `UPDATE ${this.tableName} SET ${columnSet} WHERE id = ?`

      await db.query(sql, [...values, id])
    } catch (error) {
      throw new Error(error)
    }
  }

  /**
   * find one tag
   * @param {*} params
   */
  async findOne (params) {
    try {
      const { columnSet, values } = multipleColumnSet(params, ' AND ')

      const sql = `SELECT s.id, s.tagName, s.userId FROM ${this.tableName} s WHERE ${columnSet}`

      const result = await db.query(sql, values)

      return result[0]
    } catch (error) {
      throw new Error(error)
    }
  }

  /**
   * delete site
   * @param { String } id
   */
  async delete (id) {
    try {
      const sql = `DELETE FROM ${this.tableName} WHERE id = ?`

      await db.query(sql, [id])
    } catch (error) {
      throw new Error(error)
    }
  }
}

module.exports = new TagModel()
